<!DOCTYPE html>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Js实现图片放大镜效果</title>
<style type="text/css">
*{
  margin:0px;
  padding:0px;
}
#container{
  width:400px;
  height:400px;
  margin:100px;
  margin-left:17%;
  position:relative;//这里使用相对定位，好让其他的元素能依靠这个元素定位
}
#point{
  background-color:blue;
  opacity: 0.2;
  width:220px;
  height:220px;
  position:absolute;
  left:0px;
  top:0px;
  display:none;//先让他隐藏，用js使其显示
}
#wrapper{
  width:400px;
  height:400px;
  overflow:hidden;
  position:absolute;
  top:0px;
  left:450px;
  display:none;//先让他隐藏，用js使其显示
}
#wrapper img{
  width:800px;
  height:800px;
  position:absolute;
  top:0px;
  left:0px;
}
</style>

</head>
<body>
<div id="container">
    <img src="http://img.taopic.com/uploads/allimg/140513/235059-14051310145412.jpg" width="400" height="400" alt="#">
    <div id="point"></div>
    <div id="wrapper">
      <img id="bigImg" src="http://img.taopic.com/uploads/allimg/140513/235059-14051310145412.jpg" alt="#">
    </div>
</div>
</body>
<script type="text/javascript">
 (function(){
    var container = document.getElementById("container");
    var point = document.getElementById("point");
    var wrapper = document.getElementById("wrapper");
    var bigImg = document.getElementById("bigImg");
    container.onmouseover = function(){//鼠标移动到box上显示大图片和选框
      wrapper.style.display = "block";
      point.style.display="block";
    }
    container.onmouseout = function(){//鼠标移开box不显示大图片和选框
      wrapper.style.display = "none";
      point.style.display="none";
    }
    container.onmousemove = function(e){//获取鼠标位置
      var x = e.clientX;//鼠标相对于视口的位置
      var y = e.clientY;
      var t = container.offsetTop;//container相对于视口的位置
      var l = container.offsetLeft;
      console.log('x='+x+'---l='+l);
      console.log('point.offsetWidth='+point.offsetWidth+'---point.offsetHeight='+point.offsetHeight);
      var _left = x - l - point.offsetWidth/2;//计算point的位置
      var _top = y - t -point.offsetHeight/2;
      if(_top<=0){//滑到container的最顶部
        _top = 0;
      }else if(_top>=container.offsetHeight-point.offsetHeight){//滑到container的最底部
        _top = container.offsetHeight-point.offsetHeight ;
      }
      if(_left<=0){//滑到container的最左边
        _left=0;
      }else if(_left>=container.offsetWidth-point.offsetWidth){//滑到container的最右边
        _left=container.offsetWidth-point.offsetWidth ;
      }
      point.style.top = _top +"px";//设置point的位置
      point.style.left = _left + "px";
      var w = _left/(container.offsetWidth-point.offsetWidth);//计算移动的比例
      var h = _top/(container.offsetHeight-point.offsetHeight);
      var bigImg_top = (bigImg.offsetHeight-wrapper.offsetHeight)*h;//计算大图的位置
      var bigImg_left = (bigImg.offsetWidth-wrapper.offsetWidth)*w;
      bigImg.style.top = -bigImg_top + "px";//设置大图的位置信息
      bigImg.style.left = -bigImg_left + "px";
    }
})()
</script>
</html>
